#include "stdint.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <libusb-1.0/libusb.h>
#include "pthread.h"


void device_Thread()
{
int32_t ret; 
int32_t ep1, ep2;
int32_t actualLen, len;

char sendbuf[] = "USB bulk device data ...";
char readbuf[128] = {0};

//device bulk 
ep1 = open("/dev/usb-ffs/bulk2/ep1", O_RDWR);
if (ep1 < 0)
{ 
printf("open ep1 failed, ret[%d]", ret);
return -1;
}

ep2 = open("/dev/usb-ffs/bulk2/ep2", O_RDWR);
if (ep2 < 0)
{ 
printf("open ep2 failed, ret[%d]", ret);
return -1;
}

while(1)
{
//read
actualLen = read(ep2, (uint8_t *)&readbuf[0], 128);
if (actualLen < 0) 
{
printf("USB device read failed[%d]\n",actualLen);
}
else 
{
printf("USB device recive data\t\t[%s], \tlen[%d]\n", (uint8_t *)&readbuf[0], actualLen);
//send
actualLen = write(ep1, &sendbuf[0], strlen(sendbuf));
//printf("device send ... \n");
}

sleep(1);
}

close(ep1);
close(ep2);

return;
}

int main()
{
int32_t ret; 
int32_t actualLen, len;

static pthread_t deviceThread = 0;

struct libusb_device_handle *handle = NULL;

char sendbuf[] = "USB bulk host data ...";
char readbuf[128] = {0};

//host libusb 
//char sendbuf[] = "bulk linker loop";
//char readbuf[128] = {0};

ret = libusb_init(NULL);
if (ret < 0) {
printf("libusb_init failed\n");
return -1;
}

handle = libusb_open_device_with_vid_pid(NULL, 0x1d6b, 0x0104);
if (handle == NULL) {
printf("libusb_open_device_with_vid_pid failed\n");
return -1;
}

ret = libusb_claim_interface(handle, 3);//Num
if (ret != LIBUSB_SUCCESS) {
printf("libusb claim interface error, ret[%d]\n", ret);
libusb_close(handle);
return -1;
}

if (pthread_create(&deviceThread, NULL, device_Thread, NULL) != 0) {
printf("create monitor task fail.\n");
return -1;
}

sleep(2);

//send
ret = libusb_bulk_transfer(handle, 0x03, (uint8_t *) sendbuf, strlen(sendbuf), &actualLen, 50);
if (ret < 0) {
printf("libusb_bulk_transfer send failed[%d], endpointOut[%x], len[%d]\n",ret, 0x02, strlen(sendbuf));
//return -1;
}

while(1)
{
//read
memset(&readbuf[0], 0x0, sizeof(readbuf));
ret = libusb_bulk_transfer(handle, 0x84, &readbuf[0], 128, &actualLen, 50);
//printf("libusb_bulk_transfer read_len[%d], ret[%d]\n", actualLen, ret);
if (0 == ret)
printf("USB host recive data\t\t[%s], \tread_len[%d]\n", &readbuf[0], actualLen);

sleep(2);

ret = libusb_bulk_transfer(handle, 0x03, (uint8_t *) sendbuf, strlen(sendbuf), &actualLen, 50);
if (ret < 0) {
printf("USB host send failed[%d]\n",ret);
//return -1;
}
}

return 0;
}